package com.wq.httpclientcore.config;

import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
import org.apache.hc.core5.util.Timeout;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class HttpClientConfig {

    @Value("${http-client.pool.max-total}")
    private int maxTotal;

    @Value("${http-client.pool.default-max-per-route}")
    private int defaultMaxPerRoute;

    @Value("${http-client.timeout.connect}")
    private int connectTimeout;

    @Value("${http-client.timeout.request}")
    private int requestTimeout;

    @Value("${http-client.timeout.response}")
    private int responseTimeout;

    @Bean
    public PoolingHttpClientConnectionManager connectionManager() {
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
        connectionManager.setMaxTotal(maxTotal);
        connectionManager.setDefaultMaxPerRoute(defaultMaxPerRoute);
        System.out.println("createAConnectionPoolManager================>");
        return connectionManager;
    }

    @Bean
    public CloseableHttpClient httpClient(PoolingHttpClientConnectionManager connectionManager) {
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(Timeout.ofSeconds(connectTimeout))
                .setConnectionRequestTimeout(Timeout.ofSeconds(requestTimeout))
                .setResponseTimeout(Timeout.ofSeconds(responseTimeout))
                .build();
        System.out.println("createHttpClient===================>");
        return HttpClients.custom()
                .setConnectionManager(connectionManager)
                .setDefaultRequestConfig(requestConfig)
                .build();
    }
}